package com.ming.util;

import java.sql.*;

/**
 * Created by Administrator on 2018/7/30 0030.
 */
public class Database {
    //连接数据库地址jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=UTF-8传入数据库的字符需要的格式
    public static String url = "jdbc:mysql://localhost:3306/purifier?useUnicode=true&characterEncoding=UTF-8";
    private static String Uname = "root";
    private static String Upwd = "123";
    //需要加载的jdbc驱动
    private static String JDBC = "com.mysql.jdbc.Driver";

    //加载驱动 程序加载时加载驱动
    static {
        try {
            Class.forName(JDBC);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
          System.out.print("数据库连接凉了");
        }
    }

    //打开数据库连接
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, Uname, Upwd);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeConnection(Connection conn, Statement stat, ResultSet rs) {
        try {
            if (conn != null) {
                conn.close();
            }
            if (stat != null) {
                stat.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (Exception e) {
            System.out.println("关闭数据库连接失败");
        }
    }

    //增删改通用的方法
    public static int executeUpdate(String sql, Object[] ob) {
        int i = 0;
        Connection conn = getConnection();
        PreparedStatement stat = null;
        try {
            stat = conn.prepareStatement(sql);
            if (ob != null) {
                for (int j = 0; j < ob.length; j++) {
                    stat.setObject(j + 1, ob[j]);
                }
            }
            i = stat.executeUpdate();
        } catch (Exception e) {
            System.out.println("增删改异常" + e.getMessage());
        } finally {
            closeConnection(conn, stat, null);
        }
        return i;
    }
}
